package ue.client.gfx;

import java.util.ArrayList;

import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;

public class Sprite {
	
	protected static ArrayList<Sprite> sprites = new ArrayList<Sprite>();
	
	protected Image image;
	protected String path;
	protected int id;
	
	protected Sprite(String path, int id) {
		try {
			this.image = new Image("res/" + path);
		} catch (SlickException e) {
			e.printStackTrace();
		}
		this.path = path;
		this.id = id;
	}

	public Image getImage() {
		return image;
	}

	public String getPath() {
		return path;
	}

	public int getId() {
		return id;
	}
	
	//STATICS
	
	/**
	 * Loads a new sprite and adds it to the sprites, as long as it does not yet exist.
	 * 
	 * @param path The path of the sprite to be loaded.
	 * @return The ID of the loaded sprite.
	 */
	public static int loadSprite(String path) {
		int sprite = findSprite(path);
		
		if(sprite != -1) {
			return sprite;
		}
		
		sprites.add(new Sprite(path, sprites.size()));
		return sprites.size() - 1;
	}
	
	/**
	 * Returns the sprite ID if the sprite with the given path already exists, -1 otherwise.
	 * 
	 * @param path The path of the sprite to be found.
	 * @return The ID of the found sprite, -1 if the sprite was not found.
	 */
	public static int findSprite(String path) {
		for(int i = 0; i < sprites.size(); i++) {
			if(sprites.get(i).getPath().equals(path))
				return i;
		}
		return -1;
	}
	
	/**
	 * Checks if the sprite with the given ID exists.
	 * 
	 * @param id The ID of the sprite to be checked.
	 * @return True if the sprite exists, False otherwise.
	 */
	public static boolean spriteExists(int id) {
		if(id < sprites.size() && id >= 0)
			return true;
		else
			return false;
	}
	
	/**
	 * Returns the sprite image if the sprite exists.
	 * @param id The sprite ID.
	 * @return The image of the sprite, if it exists, null otherwise.
	 */
	public static Image getSpriteImage(int id) {
		if(spriteExists(id))
			return sprites.get(id).getImage();
		else
			return null;
	}
	
	/**
	 * Attempts to remove the sprite with the given ID.
	 * 
	 * @param id The ID of the sprite to be removed.
	 * @return True if the sprite was successfully removed, false otherwise.
	 */
	public static boolean removeSprite(int id) {
		if(spriteExists(id)) {
			sprites.remove(id);
			return true;
		} else {
			return false;
		}
	}
}
